package com.longy.desensitized.util.interceptor;


import com.longy.desensitized.util.EncryptDecryptUtil;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.sql.Statement;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class ResultDecryptInterceptor implements Interceptor {


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object resultObject = invocation.proceed();
        try {
            if (Objects.isNull(resultObject)) {
                return null;
            }
            if (resultObject instanceof List) {
                // 基于selectList
                List resultList = (List) resultObject;
                if (!resultList.isEmpty() && EncryptDecryptUtil.needToDecrypt(resultList.get(0))) {
                    for (Object result : resultList) {
                        //逐一解密
                        EncryptDecryptUtil.decryptObject(result);
                    }
                }
            } else {
                // 基于selectOne
                if (EncryptDecryptUtil.needToDecrypt(resultObject)) {
                    EncryptDecryptUtil.decryptObject(resultObject);
                }
            }
            return resultObject;
        } catch (Exception e) {
            log.error("解密失败", e);
        }
        return resultObject;
    }


    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

}
